package com.menu.Utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Component
@Slf4j
public class CommonUtil {

    public static String email = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    //发送人
    @Value("${spring.mail.username}")
    private String sendUser;
    @Autowired
    public JavaMailSender javaMailSender;

    /**
     * 发送邮件
     * @return
     */
    public  String  sendEmail(String toUser){
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            StringBuilder stringBuilder = new StringBuilder("您本次的验证码为: ");
            Random random = new Random();
            String temp = "";
            for (int i = 0; i < 6; i++) {
                int code = random.nextInt(10);
                temp+=code;
            }
            stringBuilder.append(temp);
            stringBuilder.append("  ，如非本人操作，请忽略此邮件。（五分钟内有效）。");
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, false);
            mimeMessageHelper.setFrom(sendUser);
            mimeMessageHelper.setTo(toUser);
            mimeMessageHelper.setSubject("验证码邮件");
            mimeMessageHelper.setText(stringBuilder.toString(),true);
            javaMailSender.send(message);
            return temp;
        }catch (Exception e){
            log.info("{}发送失败",toUser);
            e.printStackTrace();
            return null;
        }
    }

    public boolean verifyStirng(String str){
        if (str == null || str.length() == 0 || str.equals(" ")){
            return false;
        }
        return true;
    }

    public boolean verifyInteger(Integer i){
        if (i == null || i < 0){
            return false;
        }
        return true;
    }

    public boolean verifyClassfy(String str){
        if (str == null){
            return false;
        }
       String []arrays = new String[]{"锅具","餐具","烘焙","调料"};
        for (int i = 0; i < arrays.length; i++) {
            if (str.equals(arrays[i])){
                return true;
            }
        }
        return false;
    }

    public static boolean checkMobileIsOk(String mobile) {
        String regex = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(mobile);
        boolean isMatch = m.matches();
        return isMatch;
    }

    public static Map<String, String> transToMAP(Map parameterMap){
        Map<String, String> returnMap = new HashMap();
        Iterator entries = parameterMap.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()){
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj){
                value = "";
            }else if (valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                if (values.length == 0){
                    value = "";
                }else{
                    value = values[0];
                }
            }
            returnMap.put(name,value);
        }
        return returnMap;
    }

    //将字符串src里的内容如：[a,b,c,d]转换为arraylist形式
    public static ArrayList<String> splitAdd(String src) {
        ArrayList<String> ss = new ArrayList<String>();
        String a = "";
        String b = "";
        String[] s1 = src.split("(\\[)");
        for (String s : s1) {
            a = a + s;
        }
        String[] s2 = a.split("]");
        for (String sc : s2) {
            b = b + sc;
        }
        String[] s3 = b.split(", ");//多个空格
        for (String x : s3) {
            ss.add(x);
        }
        return ss;
    }

    //返回已经切割好符号的String字符串[a，b，c]变成 a，b，c
    public static String[] split(String src) {
        ArrayList<String> ss = new ArrayList<String>();
        String a = "";
        String b = "";
        String[] s1 = src.split("(\\[)");
        for (String s : s1) {
            a = a + s;
        }
        String[] s2 = a.split("]");
        for (String sc : s2) {
            b = b + sc;
        }
        String[] s3 = b.split(", ");//多了一个空格
        return s3;
    }
    //将字符串数组转化为int类型数组
    public static Integer[] StringToInt(String [] str){
        Integer array[] = new Integer[str.length];
        try{
            for(int i=0;i<str.length;i++){
                System.out.println(array[i]);
                array[i]=Integer.parseInt(str[i]);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return array;
    }

    //判断价格是否合法
    public Integer[] verifyMoney(String str){
        if (str == null){
            return null;
        }
        String []array = str.split("\\.");
        if (array.length != 2){
            return null;
        }
        Integer[] ans = new Integer[2];
        try{
            ans[0] = Integer.parseInt(array[0]);
            ans[1] = Integer.parseInt(array[1]);
        }catch (Exception e){
            log.info("价格转换错误！");
            return null;
        }
        if (ans[0] <= 0 || ans[1] < 0){
            return null;
        }
        return ans;
    }

    public static int getDay(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(System.currentTimeMillis()));
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        return day;
    }

    public static int getMonth(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(System.currentTimeMillis()));
        int month = calendar.get(Calendar.MONTH) + 1;
        return month;
    }

    public static int getYear(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(System.currentTimeMillis()));
        int year = calendar.get(Calendar.YEAR);
        return year;
    }


    /**
     * 获取ip地址
     * @param request
     * @return
     */
    public static  String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
